﻿#include "SoundSource.h"

////////////////////////////////////////////////////////////////////////////////
// class SoundSource
SoundSource::SoundSource()
    : audio(nullptr)
    , m_frequency(1000)
    , m_volume(100)
    , m_interval(SAMPLE_RATE * 0.5)
    , m_it(0) {}

SoundSource::SoundSource(int fq, int vol)
    : SoundSource() {
    m_frequency = fq;
    m_volume    = vol;
}

void SoundSource::set_frequency(int fq) {
    m_frequency = fq;
}

void SoundSource::set_volume(int vol) {
    m_volume = vol;
}

void SoundSource::set_interval(double interval) {
    m_interval = SAMPLE_RATE * interval;
}

qint64 SoundSource::readData(char* data, qint64 maxlen) {
    if (m_data.count() == 0)
        append_data();
    qint64 count = qMin(maxlen, (qint64)m_data.count());
    for (qint64 i = 0; i < count; i++)
        data[i] = m_data[i];
    m_data.erase(m_data.begin(), m_data.begin() + count);
    return count;
}

qint64 SoundSource::writeData(const char* data, qint64 len) {
    for (qint64 i = 0; i < len; i++)
        m_data.push_back(data[i]);
    return len;
}

void SoundSource::append_data() {
    for (qint64 i = m_it; i < m_it + m_interval; i++) {
        short temp = (m_volume / 100) * AMPLITUDE * sin(m_frequency * ONE_HZ * 2 * i * PI);
        m_data.append((char)temp);
        m_data.append((char)(temp >> 8));
        m_data.append((char)temp);
        m_data.append((char)(temp >> 8));
    }
    m_it += SAMPLE_COUNT;
}

void SoundSource::start() {
    if (nullptr == audio)
        audio = new QAudioOutput(QAudioDeviceInfo::defaultOutputDevice(), default_format());

    audio->start(this);
}

void SoundSource::stop() {
    audio->stop();
}